#!/usr/bin/python
# -*- coding:utf-8 -*-
# @FileName : python_test10_14.py
# Author    : myh

# 练习 10.14：验证用户　最后一个 remember_me.py 版本假设用户要么
# 已输入其用户名，要么是首次运行该程序。我们应修改这个程序，以
# 防当前用户并非上次运行该程序的用户。
from pathlib import Path
import json


def get_stored_username(path):
    """如果存储了用户名，就获取它"""
    if path.exists():
        contents = path.read_text()
        username = json.loads(contents)
        return username
    else:
        return None


def get_new_username(path):
    """提示用户输入用户名"""
    username = input("What is your name? ")
    contents = json.dumps(username)
    path.write_text(contents)
    return username


def greet_user():
    """问候用户，并指出其名字"""
    path = Path('username.json')
    username = get_stored_username(path)

    if username:
        while True:
            answer = input(f'用户名{username}是否正确?(yes/no)')
            if answer.lower() == 'yes':
                print(f"Welcome back, {username}!")
                break
            elif answer.lower() == 'no':
                username = get_new_username(path)
                print(f"We'll remember you when you come back, {username}!")
                break
    else:
        username = get_new_username(path)
        print(f"We'll remember you when you come back, {username}!")



greet_user()
